//
//  QMACacheDelegateImp.m
//  QQMiniGameSDKDemo
//
//  Created by Goyoungs on 2023/4/14.
//

#import "QMACacheDelegateImp.h"
#import "YYCache.h"

@interface QMACacheDelegateImp()
@property (nonatomic, strong) YYCache *cache;   
@end

@implementation QMACacheDelegateImp

+ (instancetype)sharedInstance {
    static QMACacheDelegateImp *imp;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        imp = [QMACacheDelegateImp new];
    });
    return imp;
}

- (instancetype)init {
    if(self = [super init]) {
        self.cache = [YYCache cacheWithName:@"demo"];
        [self.cache.memoryCache setCountLimit:80];
        [self.cache.diskCache setCountLimit:50];
        [self.cache.diskCache setCostLimit:20 * 1024];
        [self.cache.diskCache setAutoTrimInterval:60];
    }
    return self;
}


- (void)cacheData:(id<NSCoding> _Nullable)data forKey:(nonnull NSString *)key forCurrentUid:(BOOL)forCurrentUid {
    NSString *realKey = [self keyForCurrentUid:forCurrentUid key:key];
    if (realKey.length == 0) {
        return;
    }
   
    [self.cache setObject:data forKey:realKey];
}

- (id)loadDataForKey:(nonnull NSString *)key forCurrentUid:(BOOL)forCurrentUid {
    NSString *realKey = [self keyForCurrentUid:forCurrentUid key:key];
    if (realKey.length == 0) {
        return nil;
    }
    return [self.cache objectForKey:realKey];
}

- (NSString *)resourceLocalPathForUrl:(nonnull NSString *)url {
    return nil;
}

- (NSString *)keyForCurrentUid:(BOOL)forCurrentUid key:(NSString *)key {
    if(forCurrentUid) {
        NSString *uid = nil;
        if([[QQMiniAppSDKManager sharedInstance].sdkDelegate respondsToSelector:@selector(getAppUID)]) {
            uid = [[QQMiniAppSDKManager sharedInstance].sdkDelegate getAppUID];
        }
        if(uid.length == 0) {
            return uid;
        }
        return [NSString stringWithFormat:@"%@_%@",uid,key];
    }
    return [NSString stringWithFormat:@"none_%@",key];
}

@end
